//router的js
const express = require('express')
const index = express.Router();
const axios = require('axios');
var template = require('art-template');
const FormData = require('form-data')
const fs = require('fs')
const multipart = require('connect-multiparty');
const { RSA_NO_PADDING } = require('constants');
const { Z_DEFAULT_STRATEGY } = require('zlib');
const { urlencoded } = require('body-parser');
const { log } = require('console');
const session = require('express-session');
var multipartMiddleware = multipart()
index.use(express.urlencoded({ extended: false }))
index.use(express.json())

//获取主页面的主分类
index.get('/mainclassificationList',(req,res)=>{
    axios.get('/home/mainclassificationList',{headers:{token:(req.session.token?req.session.token:'')}})
    .then(data=>{
        res.send({data:data.data})
    })
    .catch(err=>{
        res.send({err})
    })
})
//获取首页所有轮播图
index.get('/query',(req,res)=>{
    axios.get("/home/query",{headers:{token:(req.session.token?req.session.token:'')}})
    .then(data=>{
        res.send({data:data.data})
    })
    .catch(err=>{
        res.send({err})
    })
})
//关注的人的动态
index.get('/follow', multipartMiddleware, (req, res) => {
    console.log(req.session)
    console.log(req.session.userMessage)
    let { userId,pageNum,pageSize } = req.query
    axios({
        method: 'get',
        url:'/home/followeeForums',
        headers: {
            'Content-Type':'application/x-www-form-urlencoded',
            token:(req.session.token?req.session.token:'')
        },
        params: {
            userId: userId||req.session.userMessage.id,
            pageNum: pageNum,
            pageSize: pageSize
        },
        // headers: { 
            
        //     // 'token':req.session.token
        // }
    }).then(data=>{
        res.status(200).json({
            key:data.data 
        })
    }).catch((err) => {
        res.send({err})
    })
})
//每日精华
index.get('/daily',(req,res)=>{
    let {pageNum} = req.query
    axios.get(`/home/daily?pageNum=${pageNum}`,{headers:{token:(req.session.token?req.session.token:'')}})
    .then(data=>{
        res.send({data:data.data})
    })
    .catch(err=>{
        res.send({err})
    })
})



//查询帖子点赞数量
index.get('/getLike', (req, res) => {
    let { postId } = req.query
    if (postId) {
        axios.get(`/index/thumbUpCount?postId=${postId}`,{headers:{token:(req.session.token?req.session.token:'')}})
            .then((data) => {
                console.log(data.data);
                res.send({ data: data.data })
            })
            .catch((err) => {
                res.send({ err: err })
            })
    }
})

//查询收藏帖子数量
index.get('/loveNum',(req,res)=>{
    let {postId} = req.query
    if(postId){
        axios.get(`/index/collectForumCount?postId=${postId}`,{headers:{token:(req.session.token?req.session.token:'')}})
        .then(data=>{
            res.send({data:data.data})
        })
        .catch(err=>{
            res.send({ err: err })
        })
    }
})


//查看点赞状态
index.get('/likeStatus', (req, res) => {
    let { postId, userId } = req.query
    if (userId, postId) {
        axios.get(`/index/likeStatus?postId=${postId}&userId=${userId}`,{headers:{token:(req.session.token?req.session.token:'')}})
            .then((data) => {
                res.send({ data: data.data })
            }).catch((err) => {
                res.send({ err })
            })
    }
})


//查看收藏帖子的状态
index.get('/lovePost',(req,res)=>{
    let {postId,userId} = req.query
    if(postId && userId){
        axios.get(`/index/collectForumStatus?postId=${postId}&userId=${userId}`,{headers:{token:(req.session.token?req.session.token:'')}})
        .then(data=>{
            res.send({data:data.data})
        })
        .catch(err=>{
            res.send({ err })
        })
    }
})
//收藏或取消收藏帖子
index.post('/love',(req,res)=>{
    let {postId,userId} = req.body
    if(userId && postId){
        axios.post(`/index/collectForum?postId=${postId}&userId=${userId}`,{headers:{token:(req.session.token?req.session.token:'')}})
        .then(data=>{
            res.send({data:data.data})
        })
        .catch(err=>{
            res.send({ err })
            
        })
    }
})

//获取专辑被收藏的数量
index.get('/loveAlbumNum',(req,res)=>{
    let {albumId} = req.query
    axios.get(`/index/collectAlbumCount?albumId=${albumId}`,{headers:{token:(req.session.token?req.session.token:'')}})
    .then(data=>{
        res.send({data:data.data})
    })
    .catch(err=>{
        res.send({err})
    })
})


//举报
index.post('/report',(req,res)=>{
    let {reportReason,reportType,reportUser,reportUserName,reportcontentId,reportedUser,reportedUserName} = req.body
    axios.post(`/user/report?reportReason=${encodeURIComponent(reportReason)}&reportType=${reportType}&reportUser=${reportUser}&reportUserName=${encodeURIComponent(reportUserName)}&reportcontentId=${reportcontentId}&reportedUser=${reportedUser}&reportedUserName=${encodeURIComponent(reportedUserName)}`,{headers:{token:(req.session.token?req.session.token:'')}})
    .then(data=>{
        res.send({data:data.data})
    })
    .catch(err=>{
        res.send({err})
    })
})
//帖子的浏览量
index.get('/lookNum',(req,res)=>{
    let {postId} = req.query
    if(postId){
        axios.get(`/index/forumViews?postId=${postId}`,{headers:{token:(req.session.token?req.session.token:'')}})
        .then(data=>{
            res.send({data:data.data})
        })
        .catch(err=>{
            res.send({ err })
        })
    }
})






//给帖子点赞或者取消
index.post('/like', (req, res) => {
    let { userId, postId } = req.body;
    axios({
        url: `/index/thumbUpForum?postId=${postId}&userId=${userId}`,
        method: 'post',
        headers: {
            'Content-Type':'application/x-www-form-urlencoded',
            token:(req.session.token?req.session.token:'')
        },
    }).then((data) => {
        res.send({ data:data.data })
    }).catch((err) => {
        res.send({ err: err })
    })
})


//获取用户基本信息
index.get('/getUserInfo',(req,res)=>{
    let {id} = req.query
    if(id){
        axios.get(`/Admin/User/queryForOne?id=${id}`)
        .then(data=>{
            
            
        })
        .catch(err=>{
            res.send({ err: err })
        })
    }
})


//修改昵称
index.post('/changeName',(req,res)=>{
    let {name,userId} = req.body
    axios.post(`/user/modifyName?userId=${userId}&name=${encodeURIComponent(name)}`,{headers:{token:(req.session.token?req.session.token:'')}})
    .then((data)=>{
        req.session.userMessage.username = name
        console.log(data)
        res.send({data:data.data})
    })
    .catch((err)=>{
        res.send({ err})
    })

})
//修改简介
index.post('/resume',(req,res)=>{
    let {resume,userId} = req.body
    axios.post(`/user/modifyResume?resume=${encodeURI(resume)}&userId=${userId}`,{headers:{token:(req.session.token?req.session.token:'')}})
    .then(data=>{
        req.session.userMessage.resume = resume
        res.send({data:data.data})
    })
    .catch(err=>{
        res.send({err})
    })
})
//修改性别
index.post('/changeSex',(req,res)=>{
    let {id,sex} = req.body
    axios.post(`/user/modifyInformation?id=${id}&sex=${encodeURIComponent(sex)}`,{headers:{token:(req.session.token?req.session.token:'')}})
    .then(data=>{
        req.session.userMessage.sex = sex
        res.send({err:0})
    })
    .catch(err=>{
        res.send({err})
    })
})
//修改城市
index.post('/changeCity',(req,res)=>{
    let {area,sex,id} = req.body
    axios.post(`/user/modifyInformation?id=${id}&area=${encodeURIComponent(area)}&sex=${encodeURIComponent(sex)}`,{headers:{token:(req.session.token?req.session.token:'')}})
    .then(data=>{
        req.session.userMessage.area = area
        res.send({err:0})
    }).catch(err=>{
        console.log(err)
    })
})
//修改邮箱
index.post('/changeEmail',(req,res)=>{
    let {id,email} = req.body
    axios.post(`/user/setEmail?email=${encodeURIComponent(email)}&id=${id}`,{headers:{token:(req.session.token?req.session.token:'')}})
    .then(data=>{
        req.session.userMessage.email = email
        res.send({data:data.data})
    })
    .catch(err=>{
        res.send({err})
    })
})
//修改密码
index.post('/changePassword',(req,res)=>{
    let {id,newPassword,password,repeatPassword} = req.body
    axios.post(`/user/modifyPasswordById?id=${id}&newPassword=${newPassword}&password=${password}&repeatPassword=${repeatPassword}`,{headers:{token:(req.session.token?req.session.token:'')}})
    .then(data=>{
        res.send({data:data.data})
    })
    .catch(err=>{
        res.send({err})
    })
})
//更换头像  修改缓存图片名称版
index.post('/changeHead', multipartMiddleware, (req, res) => {
    // let {id} = req.query
    // let file = req.files
    let {userId} = req.query
    console.log(userId)
    let file = req.files.multipartFile;
    // console.log(file)
    const uri = file.path; //获取路径
    const newUri = `${uri}.jpg`;
    //修改图片名字
    // fs.rename(uri, newUri, (err) => {
    //     if (err) {
    //         //修改图片名字出错
    //         res.send({msg: '图片处理错误'});
    //         throw  err;
    //     }
        let multipartFile = new FormData();
        multipartFile.append('multipartFile', fs.createReadStream(uri));
            axios.post(`/user/modifyAvatar?userId=${userId}`, multipartFile, { headers: multipartFile.getHeaders() })
            .then((data) => {
                req.session.userMessage.portrait = data.data.portrait
                res.send({ data: data.data })

            })
            .catch((err) => {
                res.send(err)
            })
    // })
})

//推荐关注
index.get('/recommend',(req,res)=>{
    let {userId} = req.query
    // console.log(req)
    axios({
        url:`/home/recommendFollowee?userId=${userId}`, 
        method:'get',
        headers: {
            'Content-Type':'application/x-www-form-urlencoded',
            token:(req.session.token?req.session.token:'')
        },
    }).then(data=>{
        res.send({data:data.data})
    }).catch(err=>{
        res.send({err:err})
    })
})
//没有登录状态下返回的数据
index.get('/recommendS',(req,res)=>{
    // console.log(req)
    axios({
        url:`/home/recommendFollowee`, 
        method:'get',
        headers: {
            'Content-Type':'application/x-www-form-urlencoded',
            token:(req.session.token?req.session.token:'')
        },
    }).then(data=>{
        res.send({data:data.data})
    }).catch(err=>{
        res.send({err:err})
    })
})

//热搜
index.get('/hotSearch',(req,res)=>{
    axios.get('/home/hotWord',{headers:{token:(req.session.token?req.session.token:'')}})
    .then(data=>{
        res.send({data:data.data})
    })
    .catch(err=>{
        res.send({err:err})
    })
})
//关注用户
index.post('/folloUser',(req,res)=>{
    let {followeeId} = req.body
    if(req.session==undefined){
        res.status(200).json({
            error:"/picture/login"
        })
    }else{
        if(followeeId){
            axios({
                url:`/user/followeeUser?followeeId=${followeeId}&userId=${req.session.userMessage.id}`,
                method:"post",
                headers: {
                    token:(req.session.token?req.session.token:'')
                },
            }).then(data=>{
                res.send({data:data.data})
            }).catch(err=>{
                res.send({err})
            })
        }
    }
})

//关注列表关注和取消关注
index.post('/attaction/folloUser',(req,res)=>{
    let {followeeId,userId} = req.query
    console.log(userId);
    console.log(req.session.userMessage);
    if(req.session.userMessage!=undefined||userId){
        axios({
            url:'/user/followeeUser',
            mothod:'post',
            params:{
                followeeId:followeeId,
                userId:userId||req.session.userMessage.id,
            },
            headers: {
                'Content-Type':'application/x-www-form-urlencoded',
                token:(req.session.token?req.session.token:'')
            },
        })
        .then(data=>{
            res.send({data:data.data})
        })
        .catch(err=>{
            console.log(err)
        })
    }
})


//根据id获取帖子详情
index.get(`/getPost`,(req,res)=>{
    let {postId} = req.query
    axios.get(`/index/searchForumById?postId=${postId}`,{headers:{token:(req.session.token?req.session.token:'')}})
    .then(data=>{
        res.send({data:data.data})
    })
    .catch(err=>{
        res.send({err})
    })
})



//评论相关
index.get('/getAllFatherComment',(req,res)=>{
    let {forumId,pageNum,size} = req.query
    axios.get(`/comment/searchCommentByForumId?forumId=${forumId}&pageNum=${pageNum}&size=${size}`,{headers:{token:(req.session.token?req.session.token:'')}})
    .then(data=>{
        console.log(data)
    })
    .catch(err=>{
        res.send({err})
    })
})
//发表评论
// index.


//获取用户草稿列表
index.get('/getDraftsList',(req,res)=>{
    let {userId} = req.query
    axios({
        method:'get',
        url:'/index/getDraftsList',
        params:{
            userId:userId
        },
        headers:{
            token:(req.session.token?req.session.token:'')
        }
    }).then(data=>{
        res.send({data:data.data})
    }).catch(err=>{
        res.send({err})
    })
})

//根据草稿名字获取内容
index.get('/getDrafts',(req,res)=>{
    let {draftName,userId} = req.query
    console.log(draftName)
    axios({
        method:'get',
        url:"/index/getDrafts",
        params:{
            draftName:draftName,
            userId:userId
        },
        headers:{
            token:(req.session.token?req.session.token:'')
        }
    }).then(data=>{
        console.log(data)
        res.send({data:data.data})
    }).catch(err=>{
        res.send({err})
    })
})

//保存草稿
index.post('/draft',multipartMiddleware,(req,res)=>{
    let {userId,context,draftName} = req.query
    let formData = new FormData()
    for(var a in req.files){
        console.log(req.files[a].path)
        formData.append('file',fs.createReadStream(req.files[a].path));
    }
    axios({
        url:`/index/saveDrafts?userId=${Number(userId)}&context=${encodeURIComponent(context)}&draftName=${encodeURIComponent(draftName)}`,
        data:formData,
        method:'post',
        headers:{
            'Content-type':formData.getHeaders()['content-type'],
            token:(req.session.token?req.session.token:'')
        }
    })
    .then(data=>{
        res.send({err:0,data:data.data})
    })
    .catch(err=>{
        res.send({ err })
        console.log(err)
    })
})
//删除草稿
index.post('/deleteDraft',(req,res)=>{
    let {userId,draftName} = req.body
    axios({
        method:"post",
        data:{
            userId:userId
        },
        url:`/user/deleteDraft?userId=${userId}&draftName=${encodeURIComponent(draftName)}`,
        headers: {
            'Content-Type':'application/x-www-form-urlencoded',
            token:(req.session.token?req.session.token:'')
        },
    }).then(data=>{
        res.send({data:data.data})
    }).catch(err=>{
        res.send({err})
    })
})
//发布图片文章
index.post('/publish',multipartMiddleware,(req,res)=>{
    let {albumId,classify,context,userId,draftName} = req.query
    let formData = new FormData()
    console.log('===================================================')
    for(var a in req.files){
        console.log(req.files[a]);
        formData.append('file',fs.createReadStream(req.files[a].path));
    }
    console.log("11111111111111111111111");
    // console.log(formData.get("file"));
    axios({
        method:'post',
        url:`/index/postForum?draftName=${encodeURIComponent(draftName)}&albumId=${albumId}&classify=${classify}&context=${encodeURIComponent(context)}&userId=${userId}`,
        data:formData,
        headers:{
            'Content-type':formData.getHeaders()['content-type'],
            token:(req.session.token?req.session.token:'')
        }
    }).then(data=>{
        res.send({err:0,data:data.data})
    }).catch(err=>{
        res.send({err})
    })
})



//获取用户所有的专辑
index.get('/getAlbum',(req,res)=>{
    let {albumId} = req.query
    axios.get(`/index/checkAlbumById?albumId=${albumId}`,{headers:{token:(req.session.token?req.session.token:'')}})
    .then(data=>{
        res.send({data:data.data})
    })
    .catch(err=>{
        res.send({err})
    })
})

//获取所有小标签
index.get('/getAllSmall',(req,res)=>{
    axios.get(`/home/getSmall`,{headers:{token:(req.session.token?req.session.token:'')}})
    .then(data=>{
        res.send({data:data.data})
    })
    .catch(err=>{
        res.send({err})
    })
})
//根据子标签获取父标签的id
index.get('/getFather',(req,res)=>{
    let {subClassifyId} = req.query
    axios.get(`/index/getFatherBySon?subClassifyId=${subClassifyId}`,{headers:{token:(req.session.token?req.session.token:'')}})
    .then(data=>{
        res.send({data:data.data})
    })
    .catch(err=>{
        res.send({err})
    })
})
//创建专辑
index.post('/createAlbum',(req,res)=>{
    let {userId,albumName} = req.body
    axios.post(`/user/creatAlbum?albumName=${encodeURIComponent(albumName)}&userId=${userId}`,{headers:{token:(req.session.token?req.session.token:'')}})
    .then(data=>{
        res.send({data:data.data})
    }).catch(err=>{
        res.send({err})
    })
})










//分类页面
//根据父分类ID或取它的名字
index.get(`/getFatherName`,(req,res)=>{
    let {id} = req.query
    axios.get(`/Admin/Classfy/queryForOne?id=${id}`,{headers:{token:(req.session.token?req.session.token:'')}})
    .then(data=>{
        res.send({data:data.data})
    })
    .catch(err=>{
        res.send({err})
    })
})
//获取子分类列表
index.get(`/getSon`,(req,res)=>{
    let {fatherId} = req.query
    axios.get(`/home/subclassificationList?fatherId=${fatherId},{headers:{token:(req.session.token?req.session.token:'')}}`)
    .then(data=>{
        res.send({data:data.data})
    })
    .catch(err=>{
        res.send({err})
    })
})


//获取子标签的所有帖子
index.get('/getPostBySonId',(req,res)=>{
    let {classifyId,pageNum} = req.query
    axios.get(`/home/subclassification?classifyId=${classifyId}&pageNum=${pageNum}`,{headers:{token:(req.session.token?req.session.token:'')}})
    .then(data=>{
        res.send({data:data.data})
    })
    .catch(err=>{
        res.send({err})
    })
})











//更新轮播图
index.put('/updateFigure',multipartMiddleware,(req,res)=>{
    let {href,order,word} = req.query
    //判断有没有文件
    if(req.files.multipartFile){
        let formData = new FormData()
        console.log(req.files.multipartFile.path)
        formData.append('img',fs.createReadStream(req.files.multipartFile.path));
        axios({
            method:"put",
            url:`/Admin/Slideshow/update?href=${href}&order=${order}&word=${encodeURIComponent(word)}`,
            data:formData,
            headers:formData.getHeaders()
        }).then(data=>{
            res.send({data:data.data})
        }).catch(err=>{
            res.send({err})
        })
    }else{
        axios({
            method:"put",
            url:`/Admin/Slideshow/update?href=${href}&order=${order}&word=${encodeURIComponent(word)},{headers:{token:(req.session.token?req.session.token:'')}}`,
        }).then(data=>{
            res.send({data:data.data})
        }).catch(err=>{
            res.send({err})
        })
    }
    // formData.append('file',req.files)
})




module.exports = index